package com.person.jc.web.test.certificate;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.person.jc.common.Constants;
import com.person.jc.config.GlobalConfig;
import com.person.jc.entity.TsUser;
import com.person.jc.service.base.device.BdDeviceRelationService;
import com.person.jc.service.base.standard.BdStandardMeasureScopeService;
import com.person.jc.service.test.certificate.MakeService;
import com.person.jc.service.test.inspect.BsReconditionLogService;
import com.person.jc.service.test.inspect.BsRepairRegLogService;
import com.person.jc.utils.Servlets;
import com.person.jc.utils.SessionKit;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Mac;
import java.io.File;
import java.util.*;

/**
 * Created by ailk on 2017/9/23.
 */
public class MakeController  extends Controller {
    public void init(){
        setAttr("menuId", getPara("menuId"));
        render("main.jsp");
    }

    public void list(){
        Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
        TsUser tsUser = (TsUser) SessionKit.get().getAttribute(Constants.LOGIN_USER);
        map.put("optUser", tsUser.getUserId());
        map.put("orderType","3");
        map.put("flow", Constants.FLOW_WX_WXRW);
        List<Record> list = MakeService.me.getList(map);
        setAttr("list", list);
        render("list.jsp");
    }

//    public void toMakeCertificate(){
//        String scopeId="8";
//        List<Record> rs= BdDeviceRelationService.me.getConfigureItemDataByScopeId(Integer.valueOf(scopeId));
//        setAttr("rs", JsonKit.toJson(rs));
//        setAttr("scopeId",scopeId);
//        render("cert.jsp");
//    }

    public void viewList(){ //TODO 点击订开始制证查看订单里的制证情况
        Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
        TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
        map.put("userId", tsUser.getUserId());
        List<Record> list = MakeService.me.getViewList(map);
        setAttr("list", list);
        render("viewList.jsp");
    }

    public void doMakeCertificate(){
        String orderId=getPara("orderId");
        String equId=getPara("equId");
        String scopeIds = getPara("scopes");
        String gasType=getPara("gasType");

        setAttr("rs", "\"\"");
        Map<String,Object> map=new HashMap<String,Object>();
        if(scopeIds!=null && !scopeIds.equals("")){
            String[] scopeIdArray=scopeIds.split(",");
            List<Record> rs=new ArrayList<Record>();
            for (int i = 0; i < scopeIdArray.length; i++) {
                //获得已经配置好的配置数据
                List<Record> re=BdDeviceRelationService.me.getConfigureItemDataByScopeId(Integer.valueOf(scopeIdArray[i]));
                if(re!=null && re.size()>0){
                    rs.addAll(re);
                }
            }
            setAttr("rs", JsonKit.toJson(rs));
        }

        //获取维修记录
        Record record= Db.findFirst("select * from bs_recondition_log where order_id=? and equ_id=?",orderId,equId);

        //获取原始记录提交的关键值
        List<Record> keyvalueRec=Db.find("select type,key_value from bs_certificate_key_value where order_id=? and equ_id=?",orderId,equId);
        String keyValue="";
        for (Record rec:keyvalueRec){
            keyValue+=",\""+rec.getStr("type")+"\":"+rec.getStr("key_value");
        }
        if(!keyValue.equals("")){
            keyValue= keyValue.substring(1);
            keyValue="{"+keyValue+"}";
        }else{
            keyValue="{}";
        }



        setAttr("address",record.getStr("address"));
        setAttr("remark",record.getStr("remark"));
        setAttr("gasType", gasType.toLowerCase());
        setAttr("orderId", orderId);
        setAttr("equId", equId);
        setAttr("keyValue",keyValue);


        render("cert.jsp");
    }

    public void showCertificate(){
        String orderId=getPara("orderId");
        String equId=getPara("equId");
        Record record=MakeService.me.findCertByOrderIdAndEquId(orderId,equId);
        setAttr("cert",record);


        render("showCert.jsp");

    }



    public void saveShadow(){
        String orderId=getPara("orderId");
        String equId=getPara("equId");

        String filePath=GlobalConfig.getShadowsRealPath()+orderId+"_"+equId+"/";

        List<UploadFile> uploadFiles = getFiles();//在磁盘上保存文件
        System.out.println(uploadFiles.size());

        for (UploadFile uf : uploadFiles ) {

//            logger.info(">>>>>>>UploadController uploadAttach start "+ uf.getFileName() +" >>>>>>>>>");

            String  path = filePath + uf.getFileName();

            File upFile = new File(path);

            if (!upFile.getParentFile().exists()) {

                upFile.getParentFile().mkdirs();

            }

            uf.getFile().renameTo(upFile);

//            setAttr("success", true).setAttr("filepath", uploadPath).setAttr("filename", uf.getFileName());

        }


        MakeService.me.saveShadow(orderId,equId,filePath);
        renderText("success");
    }

    public void showShadow(){
        String orderId=getPara("orderId");
        String equId=getPara("equId");
        Record r=MakeService.me.showShadow(orderId,equId);
        String paths=r.getStr("shadow_address");
        List<String> pathList=new ArrayList<String>();
        if(StringUtils.isNotBlank(paths)){
            File file = new File(paths);
            File[] files = file.listFiles();
            for (File file2 : files) {
                if (!file2.isDirectory()) {
                    pathList.add(orderId+"_"+equId+"/"+file2.getName());
                }
            }



        }

        setAttr("paths",pathList);
        render("shadowList.jsp");

    }

    public void batchPrint(){
        String orderId=getPara("orderId");
       List<Record> rs=  MakeService.me.findCertByOrderId(orderId);
       renderJson(rs);
    }

    //展现证书清单
    public void showCertificateList(){
        String orderId=getPara("orderId");
        String deviceType=getPara("deviceType");

        if(deviceType!=null){
            Record info = MakeService.me.findInfoByOrderId(orderId);
            List<Record> rs=MakeService.me.findEquipmentByOrderIdAndType(orderId,Integer.valueOf(deviceType));

            if(rs==null){
                setAttr("rsSize",0);

            }else{

                setAttr("rsSize",rs.size());
            }
            int surplus=20-rs.size();
            setAttr("info",info);
            setAttr("surplus",surplus >=0 ? surplus : 0);
            setAttr("res",rs);
            if(deviceType.equals("1")){ //1为气瓶
                render("certListQP.jsp");
            }else if(deviceType.equals("2")){ //2为空呼
                render("certListKH.jsp");
            }else if(deviceType.equals("3")){ //3为气检仪
                render("certListGas.jsp");
            }
        }else{
            List<Record> rs=MakeService.me.findDeviceTypeByOrderId(orderId);

            setAttr("orderId",orderId);
            setAttr("deviceTypes",rs);


            render("certList.jsp");
        }



    }

    public void updateValidityDate(){
        String certId=getPara("certId");
        String validityDate=getPara("validityDate");
        Db.update("update bs_recondition_log set validity_date=? where rec_id=?",validityDate,certId);
        renderText("success");
    }

}
